/*
 * Copyright (C) 2009  Sylvain Maucourt (smaucourt@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *
 */
package net.sylvek.where;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.FacebookException;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;

public class UploadPhotoService extends Service {

    private static final int WAIT_RETRY = 60000;

    private static final int RETRY_TENTATIVE = 10;

    public static final String PHOTO_TEXT = "photo_text";

    public static final String PHOTO_LOCALIZED = "photo_localized";

    private void upload(Uri content, String text, boolean isLocated) throws ClientProtocolException, IOException, JSONException,
            InterruptedException
    {
        InputStream data = getContentResolver().openInputStream(content);
        StringBuffer caption = new StringBuffer(text);
        if (isLocated) {
            Location location = WhereUtils.getLastKnownLocation(UploadPhotoService.this);
            if (location != null) {
                String url = WhereUtils.getCurrentStaticLocationUrl(UploadPhotoService.this, location);
                caption.append(" location: ");
                caption.append(WhereUtils.getTinyLink(url));
            }
        }

        int retry = RETRY_TENTATIVE;
        while (retry > 0 && fbClient != null) {
            try {
                fbClient.publish("me/photos", FacebookType.class, data, Parameter.with("message", caption.toString()));
                retry = 0;
            } catch (FacebookException e) {
                Thread.sleep(WAIT_RETRY);
                retry--;
            }
        }
    }

    @Override
    public void onLowMemory()
    {
        super.onLowMemory();
        Log.w("UploadPhotoService", "low memory detected");
    }

    @Override
    public void onStart(final Intent intent, final int startId)
    {
        super.onStart(intent, startId);
        setForeground(true); // prevent to low memory effect

        Executors.newCachedThreadPool().execute(new Runnable() {

            @Override
            public void run()
            {
                try {
                    upload(intent.getData(), intent.getStringExtra(PHOTO_TEXT), intent.getBooleanExtra(PHOTO_LOCALIZED, false));
                    String message = getString(R.string.upload_photo_success);
                    WhereUtils.sentNotification(UploadPhotoService.this, message);
                } catch (Exception e) {
                    String message = e.getMessage();
                    WhereUtils.sentNotification(UploadPhotoService.this, message);
                }
            }
        });

    }

    private FacebookClient fbClient;

    @Override
    public void onCreate()
    {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String accessToken = pref.getString(Where.STORED_ACCESS_TOKEN, null);
        if (accessToken != null) {
            fbClient = new DefaultFacebookClient(accessToken);
        }
    };

    @Override
    public IBinder onBind(Intent intent)
    {
        throw new RuntimeException("not used, use start instead");
    }

}
